package servlets;

import beans.MaintenanceBean;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import db.MaintenanceDAO;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.SQLException;
import java.text.SimpleDateFormat;

@WebServlet("/ExportMaintenanceServlet")
public class ExportMaintenanceServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        int maintenanceId = Integer.parseInt(request.getParameter("id"));
        MaintenanceDAO dao = new MaintenanceDAO();

        try {
            MaintenanceBean record = dao.getMaintenanceById(maintenanceId);
            if (record == null) {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "维修记录未找到");
                return;
            }

            // 创建PDF文档
            Document document = new Document();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PdfWriter.getInstance(document, baos);
            document.open();

            // 添加标题
            Font titleFont = new Font(Font.FontFamily.HELVETICA, 18, Font.BOLD);
            Paragraph title = new Paragraph("维修记录单", titleFont);
            title.setAlignment(Element.ALIGN_CENTER);
            title.setSpacingAfter(20);
            document.add(title);

            // 创建表格
            PdfPTable table = new PdfPTable(2);
            table.setWidthPercentage(100);
            table.setSpacingBefore(10f);
            table.setSpacingAfter(10f);

            // 设置表格列宽
            float[] columnWidths = {1f, 3f};
            table.setWidths(columnWidths);

            // 添加表格内容
            addRow(table, "单号", String.valueOf(record.getMaintenanceId()));
            addRow(table, "车牌号", record.getLicensePlate());
            addRow(table, "司机", record.getDriverName());
            addRow(table, "维修费用", "¥" + record.getCost());
            addRow(table, "维修时间", new SimpleDateFormat("yyyy-MM-dd HH:mm").format(record.getMaintenanceTime()));
            addRow(table, "状态", record.getStatus());
            addRow(table, "审核人", record.getReviewer());
            addRow(table, "用途", record.getPurpose());

            document.add(table);
            document.close();

            // 设置响应头
            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition", "attachment; filename=maintenance_" + maintenanceId + ".pdf");
            response.setContentLength(baos.size());

            // 写入响应输出流
            OutputStream os = response.getOutputStream();
            baos.writeTo(os);
            os.flush();
            os.close();

        } catch (DocumentException | SQLException e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "导出失败: " + e.getMessage());
        }
    }

    private void addRow(PdfPTable table, String label, String value) {
        Font boldFont = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD);
        Font normalFont = new Font(Font.FontFamily.HELVETICA, 12);

        PdfPCell cell1 = new PdfPCell(new Phrase(label, boldFont));
        cell1.setBorder(Rectangle.NO_BORDER);
        cell1.setPadding(5);

        PdfPCell cell2 = new PdfPCell(new Phrase(value != null ? value : "N/A", normalFont));
        cell2.setBorder(Rectangle.NO_BORDER);
        cell2.setPadding(5);

        table.addCell(cell1);
        table.addCell(cell2);
    }
}
